package com.dayuanit.dy16.atm.wx;

import com.alibaba.fastjson.JSON;
import com.dayuanit.dy16.atm.util.AccessTokenDomain;
import com.dayuanit.dy16.atm.util.ApiConnector;
import com.dayuanit.dy16.atm.util.WxUserInfoDomain;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class WxHandler {

    @Value("${wx.appid}")
    private String appId;

    @Value("${wx.redirect.uri}")
    private String redirectURI;

    @Value("${wx.code.url}")
    private String codeUrl;

    @Value("${wx.access.token.url}")
    private String accessTokenUrl;

    @Value("${wx.secret}")
    private String secret;

    @Value("${wx.user.info.url}")
    private String userInfoURI;


    /**
     *  第一步：请求CODE URL地址
     */
    public String codeRequestUrl() {
        StringBuilder sx = new StringBuilder();
        sx.append(codeUrl).append("?")
                .append("appid=").append(appId).append("&")
                .append("redirect_uri=").append(redirectURI).append("&")
                .append("response_type=code").append("&")
                .append("scope=snsapi_login");
        return sx.toString();
    }

    /**
     * 第二步 获取accessToken
     * @param code
     * @return
     */
    public AccessTokenDomain getAccessToken(String code) {
        StringBuilder sx = new StringBuilder();
        sx.append(accessTokenUrl).append("?")
                .append("appid=").append(appId).append("&")
                .append("secret=").append(secret).append("&")
                .append("code=").append(code).append("&")
                .append("grant_type=authorization_code");

        String result = ApiConnector.get(sx.toString(), null);
        System.out.println("result=" + result);

        return JSON.parseObject(result, AccessTokenDomain.class);
    }

    public WxUserInfoDomain getUserInfo(AccessTokenDomain accessTokenDomain) {
        StringBuilder sx = new StringBuilder();
        sx.append(userInfoURI).append("?")
                .append("access_token=").append(accessTokenDomain.getAccessToken()).append("&")
                .append("openid=").append(accessTokenDomain.getOpenid());

        String result = ApiConnector.get(sx.toString(), null);
        System.out.println("result=" + result);

        return JSON.parseObject(result, WxUserInfoDomain.class);
    }


}
